import './map.css';
export default {
    data:function(){
        return {
            map:null,
            areas_index:0,  //选择区域的当前下标
            coords:[],   //当前区域坐标点
            end_line:false,  //是否是整个区域的最后一条线
            areas:[]   //地图选择的活动区域
        }
    },
    props:{
        address:String,  //活动的地址
        minArea:{
            type:Number,
            default:1000
        },
        mCoords:{    //已经选择的活动区域
            type:Array,
            default:function(){
                return []
            }
        },
        showBtn:{
            type:Boolean,
            default:true
        }
    },
    watch:{
        //监听地址，获取经纬度定位
        address:function(val){
            var self = this;
            this.map.plugin('AMap.Geocoder',function(){
                var geocoder = new AMap.Geocoder();
                geocoder.getLocation(val,function(status,result){
                    if(status == 'complete'){
                        var localtion = result.geocodes[0].location;
                        var coord = [localtion.lng,localtion.lat];
                        self.map.setCenter(coord);
                    }
                });
            });
        },
        //地图中心改变
        center:function(){
            this.map.setCenter(this.center);
        },
        //选择区域变化
        coords:function(val){
            if(val.length == 1){
                this.areas.push({
                    coords:[],
                    line_color:'#428BCA',
                    line:[],
                    mark:null,
                    area:0
                });
                this.addMark([val[0][0],val[0][1]]);
            }
            if(val.length > 1){
                if(val.length > 1) this.line();
            }
        },
        //选择的区域。初始化，修改活动
        mCoords:function(val){
            if(val.length > 0){
                for(var i=0;i<val.length;i++){
                    var tempObj = {
                        coords:val[i].coords,
                        line_color:'#FF6600',
                        area:val[i].area,
                        line:[],
                        bounds:val[i].bounds
                    }
                    this.areas.push(tempObj);
                    this.coords = val[i].coords;
                    this.line();
                    this.areas_index++;
                    this.coords = [];
                }
            }
        }
    },
    mounted:function(){
      this.loadMap();
    },
    methods:{
        //加载地图
        loadMap:function(){
            this.map = new AMap.Map('louie-map',{
                zoom:18
            });
            this.mapControl();
            this.map.on('click',this.clickMap);
        },
        //地图控件
        mapControl:function(){
            let self = this;
            AMap.plugin([
                'AMap.ToolBar'
            ],function(){
                self.map.addControl(new AMap.ToolBar());
            })
        },
        //点击地图
        clickMap:function(event){
            this.coords.push([event.lnglat.lng,event.lnglat.lat]);
        },
        /**
         * 新增标记
         * @param lnglat Array 经纬度
         */
        addMark:function(lnglat){
            var markDiv = '<div class="map-mark"></div>';
            this.areas[this.areas_index].mark = new AMap.Marker({
                content: markDiv,
                position:lnglat,
                offset: new AMap.Pixel(-5,-5)
            });
            this.areas[this.areas_index].mark.on('click',this.clickMark);
            this.map.add(this.areas[this.areas_index].mark);
        },
         /**
         * 框选区域画线
         * @param moveArr  鼠标移动时画线的经纬度数组
         */
        line:function(){
            var path = new Array();
            for(var i=0;i<this.coords.length;i++){
                path.push([this.coords[i][0],this.coords[i][1]]);
            }
             this.areas[this.areas_index].line.push(
                 new AMap.Polyline({
                     map:this.map,
                     path:path,
                     strokeWeight:3,
                     strokeColor:this.areas[this.areas_index].line_color,
                     cursor:'pointer'
                 })
             );
            if(this.end_line){
                this.coords = [];
                this.areas_index ++;
                this.end_line = false;
            }
        },
        //点击选中区域的开始坐标标记点
        clickMark:function(){
            this.end_line = true;
            this.coords.push(this.coords[0]);
            if(this.area() < this.minArea){
                this.alert('选择区域不能小于'+this.minArea+'平方米',()=>{
                    this.resetArea();
                });
                return;
            }
            this.areas[this.areas_index].coords = this.coords;
            this.areas[this.areas_index].line_color = '#FF6600';
            this.areas[this.areas_index].area = this.area();
            //取消开始标记点击事件
            this.areas[this.areas_index].mark.off('click',this.clickMark);
            this.line();
            //返回父级组件选中区域坐标
            //this.$emit('return-coords',{coords:this.coords,map:this.map,bounds:this.lineObj.getBounds(),area:this.area()});
        },
        //重置区域
        resetArea:function(){
            if(this.areas.length > 0){
                var _index = this.areas.length - 1;
                this.map.remove(this.areas[_index].line);
                if(this.areas[_index].mark) this.map.remove(this.areas[_index].mark);
                this.areas.splice(_index,1);
                this.coords = [];
                this.areas_index = _index;
            }
        },
        /**
         * 确认区域
         * @returns {*}
         */
        confirmCoords:function(){
            var areas_length = this.areas.length;
            if(areas_length <= 0){
                this.alert('请选择活动区域');
                return false;
            }
            if(this.areas[areas_length-1].coords.length <= 0){
                this.alert('请选择正确的活动区域');
                return false;
            }
            var coords = [];
            for(var i=0;i<areas_length;i++){
                var line_length = this.areas[i].line.length;
                var bounds = this.areas[i].line[line_length-1].getBounds();
                var center = bounds.getCenter();
                var lnglat1 = bounds.getSouthWest();
                var lnglat2 = bounds.getNorthEast();
                var tempObj = {
                    coords:this.areas[i].coords,
                    center:[center.lng,center.lat],
                    area:parseInt(this.areas[i].area),
                    bounds:[[lnglat1.lng.toFixed(6),lnglat1.lat.toFixed(6)],[lnglat2.lng.toFixed(6),lnglat2.lat.toFixed(6)]]
                }
                coords.push(tempObj);
            }
            console.log(coords);
            this.$emit('return-coords',coords);
        },
        //计算选中区域面积
        area:function(){
            var areaArr = [];
            for(var i=0;i<this.coords.length;i++){
                areaArr.push([this.coords[i][0],this.coords[i][1]]);
            }
            return AMap.GeometryUtil.ringArea(areaArr);
        },
        alert:function(text,call){
            var self = this;
            this.$modal.show('dialog',{
                text:text,
                buttons:[
                    {
                        title:'关闭',
                        handler:function(){
                            self.$modal.hide('dialog');
                            typeof call =='function' && call();
                        }
                    },
                ]
            });
        },
    },
    template:`
                <div id="map-box">
                    <div id="louie-map"></div>
                     <button class="btn btn-info reset-coords" type="button" @click="resetArea" v-if="showBtn">重置区域</button>
                     <button class="btn btn-success confirm-coords" type="button" @click="confirmCoords" v-if="showBtn">确定区域</button>
                     <v-dialog style="z-index:99999999999;" />
                </div>
             `
}